from po.home_page import HomePage
from selenium import webdriver
import pytest
from common.log import log
from common.sql import MysqlAuto, DBSql
from settings import ENV
from po.event import Event


@pytest.fixture(scope="class")
def login():
    driver = webdriver.Edge()  # 创建浏览器驱动
    log.debug('打开浏览器')
    driver.get(ENV.URL)  # 打开网站
    driver.maximize_window()  # 浏览器窗口最大化
    log.debug('最大化窗口')
    driver.implicitly_wait(10)  # 隐式等待 10s
    sqlite = MysqlAuto()
    sqlite.execute(DBSql.sql_list)  # 数据库初始化
    Event().event_login(driver, ENV.username, ENV.password)
    yield driver
    # 后置操作，关闭浏览器驱动
    driver.quit()
    log.debug('关闭浏览器')


@pytest.fixture(scope="class")
def open_page():
    driver = webdriver.Edge()  # 创建浏览器驱动
    log.debug('打开浏览器')
    driver.get(ENV.URL)  # 打开网站
    driver.maximize_window()  # 浏览器窗口最大化
    log.debug('最大化窗口')
    driver.implicitly_wait(10)  # 隐式等待 10s
    sqlite = MysqlAuto()
    sqlite.execute(DBSql.sql_list)
    yield driver
    # 后置操作，关闭浏览器驱动
    driver.quit()
    log.debug('关闭浏览器')


@pytest.fixture(scope="class")
def login_po():  # po模式的登录
    global driver
    driver = HomePage()
    Event.event_login_po(driver, ENV.username, ENV.password)
    yield driver
    driver.quit()


@pytest.fixture(scope="class")
def open_homepage():  # po模式的打开主页
    global driver
    driver = HomePage()
    driver.get(ENV.URL)
    yield driver
    driver.quit()


@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """
    pytest 失败后执行，函数名固定
    :param item: 测试用例
    :param call: 测试步骤
    :return: 
    """
    out = yield
    result = out.get_result()
    log.info(f'测试报告:{result}')
    log.info(f'execution time-consuming:{round(call.duration, 2)} second')
    if result.failed:
        try:
            log.info(f'error.screenshot.')
            driver.allure_save_screenshot('error_screenshot')

        except Exception as e:
            log.error(e)
            pass
